package com.tanhua.admin.listener;

import com.alibaba.fastjson.JSON;
import com.tanhua.admin.mapper.LogMapper;
import com.tanhua.model.db.Log;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * 消息监听器
 *  1、监听器交给容器管理
 *  2、编写方法（自动获取最新消息，并使用：消费）
 *      参数类型：消息类型
 *  3、方法上配置注解@RabbitListener
 */
@Component
public class LogListener {

    @Autowired
    private LogMapper logMapper;

    @RabbitListener(
            bindings = @QueueBinding(
                    value = @Queue(
                            value = "tanhua.log.queue"
                    ),
                    exchange = @Exchange(
                            value = "tanhua.log.exchange",
                            type = ExchangeTypes.TOPIC
                    ),
                    key = "log.*"
            )
    )
    public void log(String message) {
        System.out.println("获取到消息："+message);
        //1、获取消息并解析
        Map map = JSON.parseObject(message, Map.class);
        String type = map.get("type").toString();
        String logTime = map.get("logTime").toString();
        String str = map.get("userId").toString();
        Long userId = Long.valueOf(str);
        //2、构造log对象
        Log log = new Log();
        log.setUserId(userId);
        log.setLogTime(logTime);
        log.setType(type);
        //3、保存数据库
        logMapper.insert(log);
    }
}
